const AddressModel = require('../model/address')

exports.add = async (req, res, next) => {
    try {
        req.fields.uid = req.user_info.id
        let result = await AddressModel.add(req.fields)
        // console.log(result);
        res.send({ status: 'success', msg: '地址添加成功', data: { id: result[0].insertId } })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '地址添加失败' })
    }
}

exports.edit = async (req, res, next) => {
    try {
        let where = { id: req.params.id, uid: req.user_info.id }
        let result = await AddressModel.edit(req.fields, where)
        res.send({ status: 'success', msg: '地址编辑成功', data: { affectedRows: result[0].affectedRows } })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '地址编辑失败' })
    }
}

exports.delete = async (req, res, next) => {
    try {
        let result = await AddressModel.delete(req.params.id, req.user_info.id)
        res.send({ status: 'success', msg: '地址删除成功', data: { affectedRows: result[0].affectedRows } })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '地址删除失败' })
    }
}

exports.findById = async (req, res, next) => {
    try {
        // console.log(req.params);
        let result = await AddressModel.findById(req.params.id, req.user_info.id)
        res.send({ status: 'success', msg: '地址查找成功', data: result })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '地址查找失败' })
    }
}

exports.findByUid = async (req, res, next) => {
    try {
        let result = await AddressModel.findByUid(req.user_info.id)
        res.send({ status: 'success', msg: '地址查找成功', data: result })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '地址查找失败' })
    }
}

exports.findByDefault = async (req, res, next) => {
    try {
        let result = await AddressModel.findByDefault(req.user_info.id)
        res.send({ status: 'success', msg: '地址查找成功', data: result })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '地址查找失败' })
    }
}

exports.setDefault = async (req, res, next) => {
    try {
        let result = await AddressModel.setDefault(req.user_info.id, req.params.id)
        res.send({ status: 'success', msg: '默认地址设置成功', data: result })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '地默认地址设置失败' })
    }
}